/**
 * 参数对象互转
 */
export const stringObject = data => {
	if (typeof data === "string") {
		data = data.split("?").pop();
		//去掉首尾 & 
		if (data[0] === "&") {
			data = data.replace(/&/, '');
		}
		if (data[data.length - 1] === "&") {
			data = data.replace(/(.*)&/, '$1');
		}
		data = data.replace(/=/g, '":"').replace(/&/g, '","');
		try {
			return JSON.parse(`{"${data}"}`);
		} catch (e) {
			console.error(new Error(e));
			return {};
		}
	} else {
		try {
			data = Object.keys(data).map(x => {
				return `${x}=${JSON.stringify(data[x])}`
			}).join("&");
			return ('?' + data).replace(/"/g, '');
		} catch (e) {
			console.error(new Error(e));
			return '';
		}
	}
}

export const format = (v, format) => {
	const date = v ? new Date(v) : new Date();
	if (date == "Invalid Date") return '';
	let ret, fmt = format || 'yyyy-MM-dd HH:mm:ss';
	//yyyyMMddHHmmss
	const opt = {
		"y+": date.getFullYear().toString(), // 年
		"M+": (date.getMonth() + 1).toString(), // 月
		"d+": date.getDate().toString(), // 日
		"H+": date.getHours().toString(), // 时
		"m+": date.getMinutes().toString(), // 分
		"s+": date.getSeconds().toString() // 秒
		// 有其他格式化字符需求可以继续添加，必须转化成字符串
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
		};
	};
	return fmt;
}
/**
 * @desc 函数防抖
 * @param func 目标函数
 * @param wait 延迟执行毫秒数
 * @param immediate true - 立即执行， false - 延迟执行
 */
export const debounce = (func, wait, immediate, load) => {
	let timer, pro;
	return function() {
		let context = this,
			args = arguments;
		typeof load === "function" && load();
		if (timer) {
			clearTimeout(timer);
			console.warn("返回防抖函数缓存 Promise");
			return pro;
		};
		if (immediate) {
			let callNow = !timer;
			timer = setTimeout(() => {
				timer = null;
				pro = null;
			}, wait);
			if (callNow) {
				pro = func.apply(context, args);
				return pro;
			};
		} else {
			timer = setTimeout(() => {
				func.apply
			}, wait)
		}
	}
}
/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版，2 表定时器版
 * 时间戳版的函数触发是在时间段内开始的时候，而定时器版的函数触发是在时间段内结束的时候。
 */
export const throttle = (func, wait, type) => {
	if (type === 1) {
		let previous = 0;
	} else if (type === 2) {
		let timeout;
	}
	return function() {
		let context = this;
		let args = arguments;
		if (type === 1) {
			let now = Date.now();

			if (now - previous > wait) {
				func.apply(context, args);
				previous = now;
			}
		} else if (type === 2) {
			if (!timeout) {
				timeout = setTimeout(() => {
					timeout = null;
					func.apply(context, args)
				}, wait)
			}
		}
	}
}

/**
 * 处理url url拼接 及 添加前后斜杠
 * @param {String} host
 * @param {String} url  
 */
export const connect = (href = "", url = "") => {
	if (!url) {
		return '';
	}
	url = url + "";
	try {
		//判断是否是全链接 是则不对url做处理
		if (url.indexOf('http://') != 0 && url.indexOf('https://') != 0) {
			//判断url第一个字符不是斜杠 加上斜杠
			href && String(url)[0] != "/" && (url = "/" + url);
			//判断href结尾是否是斜杠 是删除斜杠
			if (href.indexOf("/") === href[(href.length - 1)]) {
				let h = href.split("");
				h.pop();
				href = h.join('');
			}
			//拼接连接
			return href + url;
		} else {
			return url;
		}
	} catch (e) {
		return url;
	}
}

/**
 * 数字金额大写转换(可以处理整数,小数,负数)
 *
 * @param n 数值(Number或者String)
 * @return
 * @type String
 */
export const digitUppercase = n => {
	if (typeof(n - 0) !== 'number' || isNaN(n - 0)) {
		return n;
	}
	var fraction = ['角', '分'];
	var digit = [
		'零', '壹', '贰', '叁', '肆',
		'伍', '陆', '柒', '捌', '玖'
	];
	var unit = [
		['元', '万', '亿'],
		['', '拾', '佰', '仟']
	];
	var head = n < 0 ? '欠' : '';
	n = Math.abs(n);
	var s = '';
	for (var i = 0; i < fraction.length; i++) {
		s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
	}
	s = s || '整';
	n = Math.floor(n);
	for (var i = 0; i < unit[0].length && n > 0; i++) {
		var p = '';
		for (var j = 0; j < unit[1].length && n > 0; j++) {
			p = digit[n % 10] + unit[1][j] + p;
			n = Math.floor(n / 10);
		}
		s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
	}
	return head + s.replace(/(零.)*零元/, '元')
		.replace(/(零.)+/g, '零')
		.replace(/^整$/, '零元整');
}
//对象深合并
export const assign = (v = {}, n = {}) => {
    let K = v;
    for (let key in n) {
        if (n.hasOwnProperty(key)) {
            const type = Object
                .prototype
                .toString
                .call(K[key]);
            if (K[key] && type === "[object Object]" || type === "[object Array]") {
                K[key] = assign(v[key], n[key]);
            } else {
                K[key] = n[key]
            }
        }
    }
    return K;
}
//对象深复制
export const depthCopy = obj => {
    if (obj === null || typeof obj !== 'object') 
        return obj;
    var cpObj = obj instanceof Array
        ? []
        : {};
    for (var key in obj) 
        cpObj[key] = depthCopy(obj[key]);
    return cpObj;
}
/**
 * 递归查找集合数据
 * @param {Object} set 需要取值的对象
 * @param {String} key 取值结构 data.list.a
 */
export const getSet = (set, key) => {
    key = (key + "").split(".");
    const obj = set[key.shift()];
    return key.length
        ? getSet(obj, key.join('.'))
        : obj;
}
/**
 * 设置集合数据
 * @param {*} set 接收数据对象
 * @param {*} key 取值结构 data.list.a
 * @param {*} data 数据
 */
export const setData = (set, key, data, fun) => {
    key = (key + "").split(".");
    const k = key.shift();
    set[k] = set[k] || {};
    if (key.length) {
        set[k] = setData(set[k], key.join('.'), data, fun);
    } else {
        set[k] = typeof fun == "function"
            ? fun(set[k], data)
            : data;
    }
    return set;
}
export const msg = (title, icon) => {
	uni.showToast({
		title,
		duration: 2000,
		icon: icon || "none",
		mask: true
	});
}
export const ua = navigator.userAgent.toLowerCase(); //获取浏览器标识并转换为小写
export const isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //是否苹果
export const isAndroid = ua.indexOf('android') > -1 || ua.indexOf('adr') > -1; //是否安卓
export const isPC = (function() {
	var Agents = new Array("android", "iphone", "symbianOS", "windows phone", "ipad", "ipod");
	var flag = true;
	for (var v = 0; v < Agents.length; v++) {
		if (ua.indexOf(Agents[v]) > 0) {
			flag = false;
			break;
		}
	}
	return flag;
})(); //是否PC
export const isWX = ua.match(/MicroMessenger/i) == "micromessenger"; //是否微信
export const isQQ = ua.indexOf(' qq/') > -1; //是否QQ
export const isDD = ua.includes('dingtalk');
